import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import {
  Grid,
  Typography,
  TableContainer,
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableCell,
  Chip,
  Box,
  useTheme
} from '@mui/material';

// Icons
import CreditCardIcon from '@mui/icons-material/CreditCard';
import PaymentIcon from '@mui/icons-material/Payment';
import StarIcon from '@mui/icons-material/Star';

// Styled Components
import {
  StyledPaper,
  StyledAppButton,
  StyledTable
} from 'components/objects/StyledComponents';

/**
 * PaymentMethodsDesktop component that displays credit cards in table view
 * 
 * @param {Object} props
 * @param {Array} props.cardsData - Array of credit card data objects
 * @param {Object} props.customerData - Customer data object with invoice settings
 * @param {boolean} props.enableCustomerPortal - Flag to enable/disable customer portal features
 * @param {Function} props.onRemoveCard - Function to handle card removal
 * @param {Function} props.onSetDefaultCard - Function to handle setting card as default
 * @param {Function} props.formatMoney - Utility function to format currency
 * @param {string} props.currency - Currency code
 */
const PaymentMethodsDesktop = ({
  cardsData = [],
  customerData,
  enableCustomerPortal = false,
  onRemoveCard,
  onSetDefaultCard,
  formatMoney,
  currency = 'USD'
}) => {
  const { t } = useTranslation();
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';

  const isDefaultCard = (cardData) => {
    if (!customerData?.invoice_settings?.default_payment_method) return false;
    
    const defaultId = typeof customerData.invoice_settings.default_payment_method === 'object'
      ? customerData.invoice_settings.default_payment_method.id
      : customerData.invoice_settings.default_payment_method;
    
    return cardData.id === defaultId;
  };

  // Header cell component for table headers
  const HeaderCell = ({ children, icon, ...props }) => (
    <TableCell 
      {...props} 
      sx={{ 
        ...(props?.sx || {}),
        color: isDarkMode ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.6)'
      }}
    >
      {icon && (
        <Box sx={{ textAlign: 'center', mb: 0.5 }}>
          {icon}
        </Box>
      )}
      {children}
    </TableCell>
  );

  return (
    <Grid item xs={12} md={6}>
      <StyledPaper darkMode={isDarkMode} sx={{ p: 3 }}>
        {/* Payment Methods Header */}
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
          <CreditCardIcon 
            color="primary" 
            sx={{ fontSize: 32, mr: 2 }}
          />
          <Typography variant="h5" component="h1">
            {t("dashboardPage.paymentMethods")}
          </Typography>
        </Box>

        {/* Table View */}
        <TableContainer>
          <StyledTable darkMode={isDarkMode}>
            <TableHead>
              <TableRow>
                <HeaderCell 
                  icon={
                    <PaymentIcon 
                      sx={{ 
                        fontSize: 24,
                        transform: 'rotate(-45deg)'
                      }}
                    />
                  }
                >
                  {t("dashboardPage.cardDetails")}
                </HeaderCell>
                <HeaderCell 
                  icon={<StarIcon sx={{ fontSize: 20 }} />}
                >
                  {t("dashboardPage.status")}
                </HeaderCell>
                {!enableCustomerPortal && cardsData.length > 1 && (
                  <HeaderCell>
                    {t("dashboardPage.actions")}
                  </HeaderCell>
                )}
              </TableRow>
            </TableHead>
            <TableBody>
              {cardsData.map((cardData, i) => (
                <TableRow 
                  key={`table-card-${i}`}
                  sx={{ 
                    '&:last-child td, &:last-child th': { border: 0 },
                    borderBottom: i < cardsData.length - 1 ? 
                      isDarkMode ? '1px solid rgba(255, 255, 255, 0.1)' : '1px solid rgba(0, 0, 0, 0.1)' : 
                      'none'
                  }}
                >
                  <TableCell>
                    <Typography>
                      {cardData.card.brand} ... {cardData.card.last4}{" "}
                      <Typography component="span" color="text.secondary">
                        {cardData.card.exp_month}/{cardData.card.exp_year}
                      </Typography>
                    </Typography>
                  </TableCell>
                  <TableCell>
                    {isDefaultCard(cardData) && (
                      <Chip 
                        icon={<StarIcon />} 
                        label={t("dashboardPage.default")}
                        color="primary"
                        size="small"
                      />
                    )}
                  </TableCell>
                  {!enableCustomerPortal && cardsData.length > 1 && (
                    <TableCell>
                      <Box sx={{ display: 'flex', gap: 1 }}>
                        {isDefaultCard(cardData) ? (
                          <StyledAppButton 
                            darkMode={isDarkMode}
                            disabled
                            size="small"
                            sx={{ minWidth: 'auto', px: 1 }}
                          >
                            {t("dashboardPage.default")}
                          </StyledAppButton>
                        ) : (
                          <>
                            <StyledAppButton
                              darkMode={isDarkMode}
                              onClick={() => onRemoveCard(cardData.id)}
                              color="error"
                              size="small"
                              sx={{ minWidth: 'auto', px: 1 }}
                            >
                              {t("dashboardPage.remove")}
                            </StyledAppButton>
                            <StyledAppButton
                              darkMode={isDarkMode}
                              onClick={() => onSetDefaultCard(cardData.id)}
                              size="small"
                              sx={{ minWidth: 'auto', px: 1 }}
                            >
                              {t("dashboardPage.default")}
                            </StyledAppButton>
                          </>
                        )}
                      </Box>
                    </TableCell>
                  )}
                </TableRow>
              ))}
            </TableBody>
          </StyledTable>
        </TableContainer>
        
        {/* Add New Card Button */}
        {!enableCustomerPortal && (
          <Box sx={{ mt: 3 }}>
            <StyledAppButton 
              darkMode={isDarkMode}
              component={Link} 
              to="/card/add" 
              variant="outlined"
              sx={{ py: 1, maxWidth: { xs: '100%', sm: '50%' } }}
              fullWidth
            >
              {t("dashboardPage.addCreditCard")}
            </StyledAppButton>
          </Box>
        )}
      </StyledPaper>
    </Grid>
  );
};

export default PaymentMethodsDesktop;